package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;

import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService{


    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public Region get(String id) {
        Region region = regionRepository.findById(id).orElse(null);
        return region;
    }

    @Override
    public List<Region> list() {

        return regionRepository.findAll();
    }

    @Override
    public Page<Region> queryPageList(QueryObject qo) {
      /*  //查询对象
        Query query = new Query();
        //查询总数据条数
        long count = template.count(query, Region.class);
        if(count==0){
            return Page.empty();
        }
        //分页排序查询
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        Query query1 = query.with(pageable);
        List<Region> list = template.find(query1, Region.class);

        return new PageImpl<Region>(list,pageable,count);*/

        Query query = new Query();
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,Region.class,query,pageable);
    }

    /**
     * 改变热门状态
     * @param id
     * @param hot
     */
    @Override
    public void changeHotValue(String id, Integer hot) {
        //先根据id查对象
        Region region = regionRepository.findById(id).get();
        //设置字段
        region.setIshot(hot);
        //更新操作
        regionRepository.save(region);
    }

    /**
     * 查询热门区域集合并按照序号排序
     * @param hot
     * @return
     */
    @Override
    public List<Region> hotRegion(int hot) {
        List<Region> regionList = regionRepository.findByIshotOrderBySequence(hot);
        return regionList;
    }


}
